package com.example.sherlockzhong.plush_v2.CardIni;

/*
 * Created by DosonLeung on 2014/8/23.
 */

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.CardBeans.OrgBean;
import com.example.sherlockzhong.plush_v2.Components.adapter.OrgGridAdapter;
import com.example.sherlockzhong.plush_v2.Constants.SystemConstant;
import com.example.sherlockzhong.plush_v2.Models.PushModel;
import com.example.sherlockzhong.plush_v2.R;
import com.example.sherlockzhong.plush_v2.Subscriptions.AddOrganizationActivity;
import com.example.sherlockzhong.plush_v2.Subscriptions.OrgDetailActivity;
import com.example.sherlockzhong.plush_v2.Subscriptions.OrganizationActivity;
import com.example.sherlockzhong.plush_v2.Utils.DialogUtil;
import com.example.sherlockzhong.plush_v2.Utils.PreventFastClickUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class OrganizationIni {

    private OrganizationActivity app;
    private Context ctx;
    private int[] imgs = {R.drawable.hci};
    private String[] titles = {"HCI"};
    private String[] filepath;
    private List<Map<String, Object>> organization_list = new ArrayList<Map<String, Object>>();
    private String[] itemName = {"grid_icon", "grid_title", "del_icon"};
    private int[] itemId = {R.id.grid_img, R.id.grid_title, R.id.del_icon};
    private ImageView grid_img;
    private ArrayList<String> OrgId = new ArrayList<String>();
    private boolean isDelete = false;
    private int Length;
    private ArrayList<String> deleteQueue = new ArrayList<String>();
    private int responseSize = 0;
    private boolean modify = false;
    private OrgGridAdapter OGA;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //Done后或者Cancel后跳转
            if (msg.what == 0x401) {
                app.stopReflashDialog();
                Toast.makeText(app.getApplicationContext(), "网络超时", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x123) {
                addResponseSize();
                if (responseSize == deleteQueue.size()) {
                    app.stopReflashDialog();
                    new Thread() {
                        @Override
                        public void run() {
                            Object o = PushModel.listSubscribedPosters();
                            if (o != null) {
                                handler.sendEmptyMessage(0x200);
                            } else {
                                handler.sendEmptyMessage(0x401);
                            }
                        }
                    }.start();
                }
            } else if (msg.what == 0x200) {
                app.stopReflashDialog();
                Toast.makeText(app.getApplicationContext(), "保存成功！", Toast.LENGTH_SHORT).show();
                app.finish();
            } else if (msg.what == 0x201) {
                if (OGA != null) {
                    int lastIndex = OGA.getBitmapList().size() - 1;
                    HashMap<String, Object> item = OGA.getBitmapList().get(lastIndex);
                    Integer index = (Integer) item.get("index");
                    Bitmap bitmap = (Bitmap) item.get("bitmap");
                    (OGA.getImageList().get(index)).setImageBitmap(bitmap);
                }
            }
        }
    };

    public OrganizationIni(OrganizationActivity app, Context ctx) {
        this.app = app;
        this.ctx = ctx;
    }

    public int getLength() {
        return Length;
    }

    public void setLength(int length) {
        Length = length;
    }

    public void init(final int lengths, final JSONArray posterArray, final OrgBean org) {
        final int length;
        if (lengths < 0) {
            length = 0;
        } else {
            length = lengths;
        }
        titles = new String[length];
        filepath = new String[length];
        org.setLength(length);
        setLength(length);

        try {
            if (posterArray != null)
                for (int i = 0; i < Length; i++) {
                    JSONObject posterObject = posterArray.getJSONObject(i);
                    filepath[i] = posterObject.getString("logo_path");
                    titles[i] = posterObject.getString("name");
                    OrgId.add(posterObject.getString("id"));
                    org.setTitles(titles);
                    org.setFilepath(filepath);
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        organization_list = org.generateTransList();
        GridView organization_gridview = (GridView) app.findViewById(R.id.organization_list);

        //为表格设置Adapter
        OGA = new OrgGridAdapter(app, handler, organization_list, R.layout.subscription_organization_grid, itemName, itemId);
        organization_gridview.setAdapter(OGA);

        //grid监听事件
        organization_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int length = getLength();
                if (position == length) {
                    PreventFastClickUtil.setInterval(2000);
                    if (PreventFastClickUtil.isFastDoubleClick())
                        return;
                    view.setClickable(false);
                    grid_img = (ImageView) view.findViewById(R.id.grid_img);
                    final Animation anim = AnimationUtils.loadAnimation(app, R.anim.rotate45);
                    grid_img.startAnimation(anim);
                    anim.setFillAfter(true);
                    final View innerView = view;
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            innerView.setClickable(true);
                            nextActivity();
                        }
                    }, 200);
                } else if (position == length + 1) {
                    //按减号
                    if (isDelete) {
                        organization_list = org.changeListToTransparent(organization_list);
                        OGA.notifyDataSetChanged();
                        isDelete = false;
                    } else {
                        organization_list = org.changeListToBeDelete(organization_list);
                        OGA.notifyDataSetChanged();
                        isDelete = true;
                    }
                } else {
                    if (isDelete) {//社团图标在此
                        //deleteQueue.clear();
                        //responseSize = 0;
                        modify = true;
                        organization_list = org.removeItem(organization_list, position, length);
                        setLength(--length);
                        final String ID = OrgId.get(position);
                        OrgId.remove(position);
                        deleteQueue.add(ID);
                        OGA.notifyDataSetChanged();
                    } else {
                        toOrgDetailActivity(id);
                    }
                }
            }
        });

        LinearLayout org_back = (LinearLayout) app.findViewById(R.id.org_back);
        org_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (responseSize != deleteQueue.size() || modify) {
                    DialogUtil.showDialog(app, "确认返回?");
                } else {
                    app.finish();
                }
            }
        });

        TextView done = (TextView) app.findViewById(R.id.org_done);
        done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDelete) {
                    if (responseSize != deleteQueue.size() || modify)
                        pushDeleteQueue();
                    else
                        app.finish();
                } else {
                    if (responseSize != deleteQueue.size()) {
                        pushDeleteQueue();
                        //app.showReflashDialog("保存中...");
                    } else {
                        app.finish();
                    }
                }
            }
        });
    }

    private void nextActivity() {
        SystemConstant.updateOrgs = false;
        Intent intent = new Intent(ctx, AddOrganizationActivity.class);
        ctx.startActivity(intent);
    }

    public void reverse() {
        final Animation anim = AnimationUtils.loadAnimation(app, R.anim.reverse_rotate);
        if(grid_img!=null){
            grid_img.startAnimation(anim);
            anim.setFillAfter(true);
        }
    }

    //开始OrgDetailActivity时 发送消息
    private void toOrgDetailActivity(long id) {
        Intent intent = new Intent(ctx, OrgDetailActivity.class);
        Bundle bundle = new Bundle();
        int ID = (int) id;
        bundle.putString("OrgId", OrgId.get(ID));
        intent.putExtras(bundle);
        app.startActivityForResult(intent, 1);
    }

    private void pushDeleteQueue() {
        int length = deleteQueue.size();
        app.showReflashDialog("保存中...");
        for (int i = 0; i < length; i++) {
            final int k = i;
            new Thread() {
                @Override
                public void run() {
                    boolean ok = PushModel.subscribe(deleteQueue.get(k), false);
                    if (ok) {
                        handler.sendEmptyMessage(0x123);
                    } else {
                        handler.sendEmptyMessage(0x401);
                    }
                }
            }.start();
        }
    }

    private synchronized void addResponseSize() {
        responseSize++;
    }

}
